//
//  ATLocal.m
//  GoBangGraduationProject
//
//  Created by 叶敦聪 on 2017/9/10.
//  Copyright © 2017年 dahua. All rights reserved.
//

#import "ATLocal.h"

@interface ATLocal ()
@property (nonatomic, strong) YTKKeyValueStore *resDB;
@property (nonatomic, strong) DHUserModel *user;
@end

@implementation ATLocal

static ATLocal *_instance;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
- (YTKKeyValueStore *)resDB {
    if (_resDB == nil) {
        _resDB = [[YTKKeyValueStore alloc] initDBWithName:@".GobangDataResource"];
        [_resDB createTableWithName:[self localStroeTableName]];
    }
    return _resDB;
}
- (NSString *)localStroeTableName {
    return @"GobangLocalStore";
}

- (void)clearUserData {
    ATLocal *local = [ATLocal sharedInstance];
    [local.resDB deleteObjectById:local.userId fromTable:local.localStroeTableName];
}

#pragma mark - 用户数据 持久化
- (NSString *)userId {
    return @"userId";
}
+ (void)updateUser:(DHUserModel *)user {
    ATLocal *local = [self sharedInstance];

    local.user = user;
    [local.resDB putObject:user.mj_keyValues withId:local.userId intoTable:local.localStroeTableName];

    [self reloadUser];
}
+ (DHUserModel *)user {
    ATLocal *local = [self sharedInstance];
    if (!local.user) {
        [self reloadUser];
    }
    return local.user;
}
+ (void)reloadUser {
    ATLocal *local = [self sharedInstance];
    local.user = [DHUserModel mj_objectWithKeyValues:[local.resDB getObjectById:local.userId fromTable:local.localStroeTableName]];
}

@end
